<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Script to show all the assignments that have not been upgraded after the main upgrade.
 *
 * @package    tool_assignmentupgrade
 * @copyright  2012 NetSpot
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

defined('MOODLE_INTERNAL') || die();

require_once(dirname(__FILE__) . '/../../../config.php');

function reset_assignment_modules()
{
    global $DB;
    $assignments = implode(',', $DB->get_fieldset_select('assignment', 'id', array()));
    $sql = "UPDATE mdl_course_modules AS cm
        SET cm.module = 1
        WHERE cm.instance IN ({$assignments})";
    
    // изменяем module заданий на значение по умолчанию
    $DB->execute($sql);
    
    // получим массив измененных записей
    $sql = "SELECT id, instance FROM mdl_course_modules AS cm WHERE cm.instance IN ({$assignments});";
    $records = $DB->get_records_sql($sql);

    $ids = array();
    foreach( $records as $value )
    {// в качестве ключа id задания 
        $ids[$value->instance][] = $value->id;
    }
    
    $del_ids = array();
    foreach($ids as $key => $value)
    {// для каждого эл-та убираем максимальный id
        if ( ! empty($value) )
        {// эл-т не пустой - удалим максимальный 
            $ids[$key] = array_diff($ids[$key], array(max($value)));
        }
        // добавляем оставшиеся значения в массив удаляемых id
        $del_ids = array_merge($del_ids, $ids[$key]);
    }
	
    // удаление дублирующих записей
    $del_ids = implode(',', $del_ids);
    if ( ! empty($del_ids) )
	{// есть id - удалим
        $select = "id IN ( ".$del_ids.")";
        return $DB->delete_records_select('course_modules', $select);
    }
    return false;
}

?>